package com.ali.service.impl;

import com.ali.api.PayApi;
import com.ali.common.Response;
import com.ali.common.UUIDUtil;
import com.ali.dao.OrderMapper;
import com.ali.entity.Order;
import com.ali.service.SeataService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SeataServiceImpl implements SeataService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private PayApi payApi;

    /**
     * GlobalTransactional：全局事务
     */
    @GlobalTransactional(name = "seata", rollbackFor = Exception.class)
    @Override
    public Response<String> seata(Map<String, Object> param) {
        //增加订单，状态为待支付
        Order order = new Order();
        order.setOrderNo(UUIDUtil.getUUID());
        order.setStatus(0);
        orderMapper.insert(order);

        //增加支付记录
        Map<String, Object> payParam = new HashMap<>() {{
            put("orderid", order.getId());
            put("payno", param.get("payno"));
            put("paymoney", param.get("paymoney"));
        }};
        payApi.add(payParam);

        //修改订单，状态为已支付
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", order.getId());
        updateWrapper.set("status", 1);
        orderMapper.update(updateWrapper);

        return Response.success("事务结束");
    }
}